<template>
  <div class="game-details">
    <nut-navbar class="navbar" z-index="5" :clickable="false">
      <template #left>
        <iconpark-icon @click="router.push('/')" class="close" icon-id="tongyicontyfanh" size="2.4rem"></iconpark-icon>
        <span>{{ gameName }}</span>
      </template>
      <template #right>
        携带金额 {{ roleInfo.money }}
      </template>
    </nut-navbar>
    <div class="content">
      <div class="tab">
        <div v-for="(v, i) in gameKinds" :key="i" :class="{ tab_ac: activeTab == v?.kindId }" @click="onClickTab(v)">
          <p>{{ unserialize(v.kind_name) }}</p>
        </div>
        <div :class="{ tab_ac: activeTab == TabType.FAVORITE }" @click="onClickFavorite(TabType.FAVORITE)">
          <p>{{ t("common_favorite") }}</p>
        </div>
      </div>

      <div class="query">
        <template v-if="activeTab != TabType.FAVORITE">
          <nut-input v-model="queryGame" placeholder="在这里输入游戏名称...">
            <template #left>
              <iconpark-icon icon-id="majesticonssearch-line" size="1.2rem" class="refresh"></iconpark-icon>
            </template>
          </nut-input>
          <Btn class="search_btn" height="39px" width="100px" fontSize="16px" @click="onClickSearch">查询</Btn>
        </template>
      </div>
      <div class="main_content">
        <template v-if="activeTab == TabType.FAVORITE">
          <div class="game-list" v-if="favoriteData.length">
            <div class="item" v-for="(v, i) in favoriteData" :key="i" @click="onPlayGameFav(v)">
              <div class="cover">
                <img :src="imgPrefix + v.gamePictureH5" alt="" />
                <iconpark-icon name="xin01" class="fav" size="25" @click.stop="onAddFavorite(v)"
                  v-if="isFav(v)"></iconpark-icon>
                <iconpark-icon name="xin02" class="fav" size="25" @click.stop="onAddFavorite(v)" v-else></iconpark-icon>
              </div>
              <div class="title">{{ unserialize(v.name) }}</div>
            </div>
          </div>
          <nut-empty v-else :description="t('nomore_data')"></nut-empty>
        </template>
        <template v-else>
          <nut-infinite-loading v-model="loading" @load-more="pullup" :threshold="500">
            <nut-pull-refresh v-model="refreshing" @refresh="pulldown">
              <nut-empty v-if="!loading && !state.list.length" :description="t('nomore_data')"></nut-empty>
              <div class="game-list" v-else>
                <div class="item" v-for="(v, i) in state.list" :key="i" @click="onPlayGame(v)">
              
                  <div class="cover">
                    <img :src="imgPrefix + v.gamePictureH5"  :alt="unserialize(v.name) " />
                    <iconpark-icon name="xin01" class="fav" size="25" @click.stop="onAddFavorite(v)"
                      v-if="isFav(v)"></iconpark-icon>
                    <iconpark-icon name="xin02" class="fav" size="25" @click.stop="onAddFavorite(v)"
                      v-else></iconpark-icon>
                  </div>
                  <div class="title">{{ unserialize(v.name) }}</div>
                </div>
              </div>
            </nut-pull-refresh>
          </nut-infinite-loading>
        </template>
      </div>
    </div>
    <Loading v-model:visible="isLoading" ></Loading>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { onBeforeMount, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import Btn from "@/components/Btn.vue";
import { storeToRefs } from 'pinia';
import { Page } from '@/store/page';
import pinia from '@/store';
import { NetPacket } from '@/netBase/NetPacket';
import { Net } from '@/net/Net';
import { NetMsgType } from '@/netBase/NetMsgType';
import { MessageEvent2 } from '@/net/MessageEvent2';
import { useI18n } from 'vue-i18n';
import { Local } from '@/utils/storage';
import { showToast } from '@nutui/nutui';
import { User } from '@/store/user';
import Loading from '@/components/Loading.vue'

const router = useRouter()
const route = useRoute()
const isLoading = ref(false)

const {
  lang,
  homeGameData
} = storeToRefs(Page(pinia));
const { roleInfo } = storeToRefs(User(pinia));

const { t } = useI18n();

const activeTab = ref<any>(0)
const queryGame = ref("")

// 加载更多
const loading = ref(false)
const refreshing = ref(false)
const state = reactive({
  currentGame: null as any,
  page: 1,
  total_page: 0,
  list: [] as any
})


let gameName = ref('')
let gameKinds = ref<any>([])
let favoriteData = ref<any[]>([])
let resultList: any = reactive([])
let pageSize = ref<number>(10)
let platformId = ref<any>(0)
let venueId = ref<any>(0)
let isVenudId = ref<boolean>(false)
let activeKind = ref<any>(0)
let threeGameKinds = ref<any[]>([])
const imgPrefix = 'http://18.162.112.52:8033/uploads/'
const TabType = {
  FAVORITE: 88
}

const getHomeData = () => {
  const data  = homeGameData.value[activeKind.value]?.three_platform
  const item = data?.find((e: any) => e.name[lang.value].toUpperCase() == gameName.value)
  threeGameKinds.value = item?.three_game_kind
}

const isFav = (v: any) => {
  return favoriteData.value.some((e: any) => e.gameId == v.gameId)
}

const handlePlatform = (res: any) => {
  resetData()
  if (res.kind && res.kind.length) {
    gameKinds.value = res.kind
    if (!isVenudId.value) {
      activeTab.value = venueId.value
      isVenudId.value = true
    }
  } else {
    const kinds = threeGameKinds.value.map((e: any) => { return { 'kindId': e.id, 'kind_name': JSON.stringify(e.name) } })
    gameKinds.value = kinds
  }
  state.list = res.info
  refreshing.value = false
}

const handleGames = (res: any) => {
  state.list.push(...res.info)
  state.total_page = Math.ceil(res.total / 10)
  loading.value = false
}

const handleQuery = (res: any) => {
  state.list = res.info
}

const onPlayGame = async (v: any) => {
  if (!Local.get('user')) {
      await User(pinia).setLogin(true)
      return
  }
  let langObj: any = {
    'en-US': 3,
    'vi-VN': 2,
    'zh-CN': 1
  }
  state.currentGame = v

  isLoading.value = true
  let tb = NetPacket.req_3rd_game_login();
  tb.agentId = platformId.value;
  tb.kindId = venueId.value;
  tb.gameId = v.gameId;
  tb.lang = langObj[lang.value];
  Net.instance.sendRequest(tb);
}

const onPlayGameFav = async (v: any) => {
  if (!Local.get('user')) {
      await User(pinia).setLogin(true)
      return
  }
  let langObj: any = {
    'en-US': 3,
    'vi-VN': 2,
    'zh-CN': 1
  }
  state.currentGame = v
  const favorites = Local.get('favorites') || []
  const data = favorites.map((e:any) => {return {'gameId': e.split('__')[0], 'agentId': e.split('__')[1], 'kindId': e.split('__')[2], 'img': e.split('__')[3]}})
  const item = data.find((e:any) => e.gameId == v.gameId)
  isLoading.value = true
  let tb = NetPacket.req_3rd_game_login();
  tb.agentId = item.agentId;
  tb.kindId = item.kindId;
  tb.gameId = item.gameId;
  tb.lang = langObj[lang.value];
  Net.instance.sendRequest(tb);
}

const onClickTab = (v: any) => {
  activeTab.value = v.kindId
  resetData()
  queryData()
}

const onClickFavorite = (i: number) => {
  activeTab.value = i
  getFavs()
}

const onClickSearch = () => {
  if (!queryGame.value) {
    showToast.fail(t('player_info_tip_1'))
    return
  }
  let tb = NetPacket.req_look_for_game_name()
  tb.agentId = platformId.value;
  tb.kindId = activeTab.value;
  tb.name = queryGame.value
  Net.instance.sendRequest(tb)
}

const getFavs = () => {
  const gameId = Local.get('favorites') || []
  const gameIds = gameId.map((e:any) => e.split('__')[0])
  favoriteData.value = resultList.filter((e: any) => gameIds.includes(e.gameId))
}

const onAddFavorite = (v: any) => {
  let favorites = Local.get('favorites') || []
  const gameIds = favorites.map((e:any) => e.split('__')[0])
  if (gameIds.includes(v.gameId)) {
    favorites = favorites.filter((e: any) => e.split('__')[0] != v.gameId)
  } else {
    const item = v.gameId + '__' +  platformId.value + '__' + activeTab.value + '__' + imgPrefix + v.gamePictureH5
    favorites.push(item)
  }
  Local.set('favorites', favorites)
  getFavs()
}

const unserialize = (v: string) => {
  const data = JSON.parse(v)
  return data[lang.value]
}

const getInitData = (agentId: any, kindId: any) => {
  const req = NetPacket.req_get_kind_in_platform();
  req.agentId = agentId
  req.kindId = kindId
  req.pageSize = pageSize.value
  Net.instance.sendRequest(req);
}

const resetData = () => {
  loading.value = false
  state.page = 1
  state.total_page = 0
  state.list = []
}

const pullup = () => {
  if (state.total_page && state.total_page <= state.page) {
    loading.value = false
    return
  }
  state.page++
  queryData()
}

const pulldown = () => {
  resetData()
  getInitData(platformId.value, activeTab.value)
}
const queryData = () => { // 查询
  loading.value = true
  const query = NetPacket.req_get_games_in_platform()
  query.agentId = platformId.value
  query.kindId = activeTab.value
  query.page = state.page
  query.pageSize = pageSize.value
  Net.instance.sendRequest(query);
}

// 第三方游戏信息返回
const gameUrlResult = (message: any) => {
  isLoading.value = false
  if (message.code != 0) {
    showToast.fail(message.msg)
    return
  }
  // let screenOrientation = '0' //默认竖屏
  if (message.url.indexOf('<!doctype html>') != -1) {
    message.url = `data:text/html;charset=utf-8,${encodeURIComponent(
      String(message.url)
    )}`
  }
  Local.set('gameUrl', message.url)
  router.push({
    path: "/openGame",
    query: {
      screenOrientation: state.currentGame.direction
    }
  });
}

onBeforeMount(() => {
  const { platform_id, venue_id, name, active } = route.query
  getInitData(platform_id, venue_id)
  gameName.value = name as string
  platformId.value = platform_id
  venueId.value = venue_id
  activeKind.value = active
  getHomeData()
})
onMounted(() => {
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_get_kind_in_platform, handlePlatform);
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_get_games_in_platform, handleGames);
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_look_for_game_name, handleQuery);
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_3rd_game_login_result,
    gameUrlResult,
  );

  getFavs()
})
onUnmounted(() => {
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_kind_in_platform, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_games_in_platform, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_look_for_game_name, null);
  MessageEvent2.removeMsgEvent(
    NetMsgType.msgType.msg_notify_3rd_game_login_result,
    null,
  );
})
watch(
  () => state.list,
  (a: any) => {
    const res = resultList?.map((e: any) => e.gameId)
    for (let e of a) {
      if (e && !res.includes(e.gameId)) {
        resultList.push(e)
      }
    }
    getFavs()
  },
  { deep: true, }
)
</script>

<style scoped lang="scss">
div.game-details {
  display: grid;
  grid-template-rows: auto 1fr;

  .navbar {
    // margin-top: 10px;
    margin-bottom: 20px;

    :deep() {
      .nut-navbar__left {
        color: #fff;

        span {
          margin-left: 10px;
        }
      }

      .nut-navbar__right {
        color: #fff;
        font-weight: normal;
        font-size: 14px;
      }
    }
  }

  .content {
    padding: 0 10px;
  }

  .main_content {
    height: calc(100vh - 240px);
    overflow-y: scroll;
  }

  .tab {
    //background: url(/imgs/email/nav_bar.webp) no-repeat center;
    background-size: 100% 100%;
    height: 45px;
    display: flex;
    gap: 9px;
    align-items: center;
    padding: 0 4px;
    width: fit-content;
    font-size: 12px;
    overflow-x: scroll;
    max-width: 94vw;

    div {
      min-width: 44px;
      height: 44px;
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #C0C2DB;
      background-image: radial-gradient(circle at 50% 13%, #4430a1 0%, #3a2786 66%, #3c279a 89%);
      border-radius: 13.1px;
      box-shadow: 0 3.7px 3.7px 0 rgba(22, 17, 46, 0.3) !important;
      font-size: 10px;
      white-space: nowrap;
    }

    .tab_ac {
      background-image: url(/imgs/home/tabActive.webp) !important;
      background-size: 100% 100%;
      color: #ffffff;
      // margin-top: 5px;
    }
  }

  .query {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &:deep(.nut-input) {
      width: 245px;
      height: 36px;
      padding: 8px;
      border-radius: 8px;
      box-shadow: inset 0 4px 4px 0 rgba(0, 0, 0, 0.25);
      border: solid 1px #322c59;
      background: radial-gradient(circle at 50% 11%, #361e79, #202137 97%) !important;

      input {
        &::placeholder {
          color: #8d84c5;
        }
      }
    }

    .search_btn {
      border-radius: 12px;
      overflow: hidden;
    }
  }

  .scroll-view {
    height: 74vh;
    overflow: auto;
  }

  .game-list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    min-height: 50vh;
    grid-template-rows: min-content;

    .cover {
      width: 110.9px;
      height: 110.9px;
      border-radius: 16.6px;
      position: relative;

      img {
        width: 100%;
        height: 100%;
      }

      .fav {
        position: absolute;
        top: 5px;
        right: 5px;
      }
    }

    .title {
      width: 85px;
      text-align: center;
      font-size: 12px;
      color: #fff;
      margin-left: auto;
      margin-right: auto;
      margin-top: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>